//
//  WKBubbleViewController.m
//  Walk
//
//  Created by cesh on 16/8/24.
//  Copyright © 2016年 cesh. All rights reserved.
//

#import "WKBubbleViewController.h"
#import "WKBubble.h"

#import "WKSettingViewController.h"
#import "WKCardViewController.h"
#import "WKChatViewController.h"


#import <EMSDK.h>
#import <AVFoundation/AVFoundation.h>
#import <SVProgressHUD.h>
#import <UIImageView+WebCache.h>
#import <IQKeyboardManager.h>
#import <CoreLocation/CoreLocation.h>
@interface WKBubbleViewController () <CLLocationManagerDelegate, UITextFieldDelegate, GoChatProtocal, EMChatroomManagerDelegate>
{
    NSArray *_bubbles;
    UIDynamicAnimator *_animator;
    UIPushBehavior *_pushBehavior;
}

/** 位置管理者 */
@property (strong, nonatomic) CLLocationManager *locationM;
@property (strong, nonatomic) CLLocation *location;

@property (assign, nonatomic) CLLocationDegrees latitude;
@property (assign, nonatomic) CLLocationDegrees longitude;

@property (strong, nonatomic) UIButton *frogBtn;

@property (strong, nonatomic) NSTimer *frogTwinkleTimer;

@property (strong, nonatomic) UIImageView *bgImg;

@property (strong, nonatomic) WKBubble *customBubble;

@property (strong, nonatomic) UITextField *customTextField;

@property (strong, nonatomic) UITapGestureRecognizer *tapOnBg;

@property (strong, nonatomic) UIImageView *bigBubble;
@property (strong, nonatomic) UILabel *bigBubbleLabel;

@property (strong, nonatomic) UILabel *countDownLabel;

@property (strong, nonatomic) UIButton *topLeftBtn;
@property (strong, nonatomic) UIButton *topRightBtn;
@property (strong, nonatomic) UIButton *topFrogBtn;

@property (strong, nonatomic) NSTimer *countDownTimer;
@property (strong, nonatomic) NSString *endTime;


@property (strong, nonatomic) NSDictionary *eventInfo;

@property (assign, nonatomic) BOOL isGoing;
@end

@implementation WKBubbleViewController

//有用户进入聊天室时候回调
- (void)didReceiveUserJoinedChatroom:(EMChatroom *)aChatroom
                            username:(NSString *)aUsername {
    
    NSLog(@"用户%@加入了聊天室%@", aUsername, aChatroom.chatroomId);
}

- (void)didReceiveUserLeavedChatroom:(EMChatroom *)aChatroom
                            username:(NSString *)aUsername {
    NSLog(@"用户%@离开了聊天室%@", aUsername, aChatroom.chatroomId);
}

- (void)didReceiveKickedFromChatroom:(EMChatroom *)aChatroom
                              reason:(EMChatroomBeKickedReason)aReason {
    NSLog(@"用户被踢出了聊天室%@ ，原因:%i", aChatroom.chatroomId, aReason);
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    
    // 注册聊天室回调
    [[EMClient sharedClient].roomManager addDelegate:self delegateQueue:nil];
    
    self.bgImg = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.bgImg.image = [UIImage imageNamed:@"loading"];
    
    [self getBubbleInfo];
    [UIView setAnimationsEnabled:YES];
    [IQKeyboardManager sharedManager].enable = NO;
    [self.view addSubview:self.bgImg];
    // 获取地理位置
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"coordinates"] == nil) {
        [self.locationM requestLocation];
    }
    else {
        CLLocation *location = [[NSUserDefaults standardUserDefaults]objectForKey:@"coordinates"];
        self.location = location;
        
    }
    
    // 上方左右的设置和消息按钮
    [self setupTopBtns];
    // 创建自定义的大气泡
    [self createBigBubble];
    
}



- (void)getBubbleInfo {
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    NSDictionary *userinfo = [NSDictionary dictionaryWithContentsOfFile:userInfoPath];
    [mgr GET:[NSString stringWithFormat:@"%@Frog/status", URL] parameters:@{@"token" : userinfo[@"token"]} progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"获取匹配状态 %@", responseObject);
        //添加背景图片
        [self.bgImg sd_setImageWithURL:responseObject[@"data"][@"backgroundImage"] placeholderImage:[UIImage imageNamed:@"loading"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            //添加底部青蛙按钮
            UIButton *frogBtn = [[UIButton alloc]init];
            [frogBtn setBackgroundImage:[UIImage imageNamed:@"frog"] forState:UIControlStateNormal];
            [frogBtn sizeToFit];
            frogBtn.center = CGPointMake(screenW * 0.5, screenH - frogBtn.height * 0.5);
            [frogBtn addTarget:self action:@selector(frogBtnSingleClick) forControlEvents:UIControlEventTouchUpInside];
            self.frogBtn = frogBtn;
            [self.view addSubview:frogBtn];
            [self.frogTwinkleTimer invalidate];
            self.frogTwinkleTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(frogTwinkle) userInfo:nil repeats:YES];
            
            //根据匹配状态设置底部青蛙可点击与否
            if ([responseObject[@"data"][@"status"] isEqualToString:@"1"]) {
                self.frogBtn.enabled = YES;
            }
            else {
                self.frogBtn.enabled = NO;
            }
            
            
            //记录聊天室相关记录
            NSArray *bubbleInfo = responseObject[@"data"][@"res"];
            self.eventInfo = responseObject[@"data"][@"eventInfo"];
            [self createBubbles:bubbleInfo];
            NSString *status = responseObject[@"data"][@"status"];
            
            [[NSUserDefaults standardUserDefaults]setObject:status forKey:@"matchStatus"];
            //如果匹配成功
            if ([status isEqualToString:@"3"]) {
                WKPopView *popV = [WKPopView showWithType:PopViewTypeGoChat];
                popV.delegate = self;
            }
        }];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"获取匹配状态 失败%@", error);
        [WKPopView showWithType:PopViewTypeTimeOut];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [WKPopView dismiss];
        });
    }];
}

- (void)goChatVC {
    [WKPopView dismiss];
    WKPopView *popV = [WKPopView showWithType:PopViewTypeGoChat];
    popV.delegate = self;
    [self.view addSubview:popV];
    [self chat];
}

- (void)countDownLabelChange {
    NSInteger countDown = (long)[self.endTime integerValue] - [[NSDate date] timeIntervalSince1970];
    NSInteger second = countDown % 60;
    NSInteger minute = (countDown / 60) % 60;
    NSInteger hour = countDown / 3600;
    self.countDownLabel.text = [NSString stringWithFormat:@"倒计时%li:%02li:%02li", (long)hour, (long)minute, (long)second];
    
    //当倒计时为0的时候, 则重新载入该界面
    if (countDown == 0) {
        WKBubbleViewController *bubbleVC = [[WKBubbleViewController alloc]init];
        CATransition *anim = [CATransition animation];
        anim.type = @"rippleEffect";
        anim.duration = 1.0;
        [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
        
        [UIApplication sharedApplication].keyWindow.rootViewController = bubbleVC;
        
        [self.countDownTimer invalidate];
        self.countDownTimer = nil;
    }
}

- (void)createBubbles:(NSArray *)bubbleInfos {
    self.isGoing = NO;
    
    NSMutableArray *ballsArray  = [NSMutableArray array];
    //球的直径在80到100之间
    for (int i = 0; i < bubbleInfos.count; i++) {
        
        NSDictionary *bubbleInfo = bubbleInfos[i];
        
        CGFloat ballSize = arc4random() % 30 + 80;
        WKBubble *bubble = [[WKBubble alloc]init];
        bubble.info = bubbleInfo;
        [bubble setOrigin:CGPointZero];
        // 如果是正在执行的活动
        [bubble setSize:CGSizeMake(ballSize, ballSize)];
        if ([bubbleInfo[@"isGoing"] isEqual:@"1"]) {
            bubble.position = CGPointMake(screenW * 0.5, screenH * 0.3);
            bubble.size = CGSizeMake(ballSize * 1.8, ballSize * 1.8);
            bubble.center = bubble.position;
        }
        //泡泡图片
        UIImageView *bubbleImg = [[UIImageView alloc]initWithFrame:bubble.bounds];
        bubbleImg.image = [UIImage imageNamed:@"paopao"];
        [bubble addSubview:bubbleImg];
        
        //给气泡添加label
        UILabel *title = [[UILabel alloc]init];
        title.text = bubbleInfo[@"name"];
        title.font = [UIFont boldSystemFontOfSize:bubble.width * 0.14];
        [title sizeToFit];
        title.textColor = [UIColor whiteColor];
        title.center = CGPointMake(bubble.width / 2, bubble.width * 0.75);
        if ([bubbleInfo[@"isGoing"] isEqual:@"0"]) {
            [bubble addSubview:title];
        }
        
        //给气泡添加图片
        UIImageView *activityImgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, bubble.width * 0.4, bubble.width * 0.3)];
        activityImgV.center = CGPointMake(bubble.width * 0.5, bubble.width * 0.5 - 10);
        //如果是正在进行的活动
        if ([bubbleInfo[@"isGoing"] isEqual:@"1"]) {
            
            //如果有正在进行的活动，记录下来
            self.isGoing = YES;
            self.topFrogBtn.tag = 2;
            self.topFrogBtn.userInteractionEnabled = YES;
            [activityImgV setSize:CGSizeMake(bubble.width * 0.4, bubble.width * 0.3)];
            activityImgV.center = CGPointMake(bubble.width * 0.5, bubble.width * 0.3 - 10);
            //剩余时间的倒计时
            NSString *endTime = bubbleInfo[@"endTime"];
            self.endTime = endTime;
            NSUInteger countDown = (long)[endTime integerValue] - [[NSDate date] timeIntervalSince1970];
            NSInteger second = countDown % 60;
            NSInteger minute = (countDown / 60) % 60;
            NSInteger hour = countDown / 3600;
            UILabel *countDownLabel = [[UILabel alloc]init];
            countDownLabel.text = [NSString stringWithFormat:@"倒计时%li:%02li:%02li", (long)hour, (long)minute, (long)second];
            countDownLabel.font = [UIFont systemFontOfSize:bubble.width * 0.12];
            [countDownLabel sizeToFit];
            [countDownLabel setWidth:countDownLabel.width + 10];
            countDownLabel.textColor = [UIColor whiteColor];
            countDownLabel.center = CGPointMake(bubble.width * 0.5, bubble.width * 0.5);
            self.countDownLabel = countDownLabel;
            [self.countDownTimer invalidate];
            self.countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDownLabelChange) userInfo:nil repeats:YES];
            
            [bubble addSubview:countDownLabel];
            //添加退出活动的按钮
            UIButton *resign = [[UIButton alloc]init];
            [resign setTitle:@"停止搜索" forState:UIControlStateNormal];
            [resign.titleLabel setFont:[UIFont systemFontOfSize:bubble.width * 0.08]];
            [resign setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [resign setBackgroundImage:[UIImage imageNamed:@"redsignBtn"] forState:UIControlStateNormal];
            [resign setBackgroundColor:[UIColor colorWithRed:0xf8 / 255.0 green:0xe7 / 255.0 blue:0x1c / 255.0 alpha:1.0]];
            resign.layer.cornerRadius = 8.0;
            resign.layer.masksToBounds = YES;
            
            [resign sizeToFit];
            resign.center = CGPointMake(bubble.width * 0.5, bubble.width * 0.8);
            [resign addTarget:self action:@selector(resignActivity:) forControlEvents:UIControlEventTouchUpInside];
            [bubble addSubview:resign];
        }
        [activityImgV sd_setImageWithURL:bubbleInfo[@"imgUrl"] placeholderImage:[UIImage imageNamed:@"default_head"]];
        [bubble addSubview:activityImgV];
        //如果是自定义的气泡
        if ([bubbleInfo[@"can_custom"] isEqual:@"1"]) {
            self.customBubble = bubble;
            [title removeFromSuperview];
            //创建一个textField
            UITextField *customTextField = [[UITextField alloc]init];
            customTextField.text = @"点此输入";
            customTextField.backgroundColor = [UIColor clearColor];
            customTextField.textAlignment = NSTextAlignmentCenter;
            customTextField.textColor = [UIColor whiteColor];
            customTextField.font = [UIFont systemFontOfSize:ballSize * 0.12];
            [customTextField sizeToFit];
            customTextField.center = CGPointMake(ballSize / 2, ballSize * 0.8);
            customTextField.tintColor = [UIColor clearColor];
            [customTextField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
            
            customTextField.delegate = self;

            if (![bubbleInfo[@"isGoing"] isEqual:@"1"]) {
                self.customTextField = customTextField;
                [bubble addSubview:customTextField];
            }
        }
        
        
        
        bubble.layer.masksToBounds = YES;
        bubble.layer.cornerRadius = ballSize / 2.0;
        

        
        //将球的动画结束后的最终定点
        NSInteger intScreenW = screenW;
        NSInteger intScreenH_2_3 = screenH * 0.67;
        if ([bubbleInfo[@"isGoing"] isEqual:@"0"]) {
            bubble.position = CGPointMake(arc4random() % intScreenW, arc4random() % intScreenH_2_3 + intScreenW / 3);
            bubble.center = bubble.position;
        }
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
        [bubble addGestureRecognizer:panGesture];

        [ballsArray addObject:bubble];
        
        [self.view addSubview:bubble];
    }
    
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"firstLaunch"]) {
        
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            // 首次进入的引导界面
            UIImageView *bubble_guide = [[UIImageView alloc]init];
            bubble_guide.frame = [UIScreen mainScreen].bounds;
            bubble_guide.image = [UIImage imageNamed:@"bubble_guide"];
            bubble_guide.userInteractionEnabled = YES;
            //添加点击删除引导界面的操作
            UITapGestureRecognizer *dismissGuide = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeGuide:)];
            [bubble_guide addGestureRecognizer:dismissGuide];
            
            [self.view addSubview:bubble_guide];
        });
    }
    
    
    _bubbles = ballsArray;
    //如果没有活动正在进行，给气泡添加点击事件
    if (!self.isGoing) {
        for (WKBubble *bubble in ballsArray) {
            [bubble addTarget:self action:@selector(clickBubble:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    
    [self createDynamicBehaviors];
    
    [self createBubbleTwinkleAnimation];
    
    [self createBubbleInitialAnimation];
}

- (void)removeGuide:(UITapGestureRecognizer *)tap {
    [tap.view removeFromSuperview];
}


- (void)setupTopBtns {
    UIButton *setting = [[UIButton alloc]initWithFrame:CGRectMake(25, 32, 45, 30)];
    [setting setImage:[UIImage imageNamed:@"nav_menu_w"] forState:UIControlStateNormal];
    setting.imageEdgeInsets = UIEdgeInsetsMake(-4, -26, 0, 0);
    [setting addTarget:self action:@selector(setting) forControlEvents:UIControlEventTouchUpInside];
    self.topLeftBtn = setting;
    [self.view addSubview:setting];
    
    UIButton *chat = [[UIButton alloc]initWithFrame:CGRectMake(screenW - 25 - 45, 32, 45, 30)];
    [chat setImage:[UIImage imageNamed:@"nav_chat_w"] forState:UIControlStateNormal];
    chat.imageEdgeInsets = UIEdgeInsetsMake(-4, 22, 0, 0);
    [chat addTarget:self action:@selector(chat) forControlEvents:UIControlEventTouchUpInside];
    self.topRightBtn = chat;
    [self.view addSubview:chat];
    
    UIButton *topFrogBtn = [[UIButton alloc]init];
    [topFrogBtn setImage:[UIImage imageNamed:@"logo_w"] forState:UIControlStateNormal];
    [topFrogBtn sizeToFit];
    topFrogBtn.center = CGPointMake(screenW * 0.5, 32 + topFrogBtn.height * 0.5);
    //未决定活动, 则顶部青蛙按钮不可点击
    topFrogBtn.tag = 1;
    topFrogBtn.userInteractionEnabled = NO;
    [topFrogBtn addTarget:self action:@selector(clickTopFrogBtn) forControlEvents:UIControlEventTouchUpInside];
    self.topFrogBtn = topFrogBtn;
    [self.view addSubview:topFrogBtn];
}

- (void)clickTopFrogBtn {
    for (WKBubble *bubble in _bubbles) {
        if ([bubble.info[@"isGoing"] isEqual:@"1"]) {
            [self clickBubble:bubble];
        }
    }
}

- (void)setting {
    WKSettingViewController *settingVC = [[WKSettingViewController alloc]init];
    CATransition *anim = [CATransition animation];
    anim.type = @"rippleEffect";
    anim.duration = 1.0;
    [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
    [self presentViewController:settingVC animated:NO completion:nil];
}

- (void)chat {
    NSString *status = [[NSUserDefaults standardUserDefaults]objectForKey:@"matchStatus"];
    if ([status isEqualToString:@"3"]) {
        WKChatViewController *chatVC = [[WKChatViewController alloc]init];
        CATransition *anim = [CATransition animation];
        anim.type = @"rippleEffect";
        anim.duration = 1.0;
        [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
        [self presentViewController:chatVC animated:NO completion:nil];
    }
    else {
        [WKPopView showWithType:PopViewTypeNotMatchYet];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [WKPopView dismiss];
        });
    }

}

#pragma mark - 懒加载
- (CLLocationManager *)locationM {
    if (_locationM == nil) {
        // 1.获取位置管理者
        _locationM = [[CLLocationManager alloc] init];
        
        // 2.设置代理
        _locationM.delegate = self;
        
        // 3.主动请求用户授权
        // 前台定位授权(如果想要在后台定位,必须开启后台模式,location updates)
        //        if (isIOS(8.0)) {
        //            [_locationM requestWhenInUseAuthorization];
        //        }
        
        // 前后台定位授权(永久); // 需要做适配
        if ([_locationM respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [_locationM requestWhenInUseAuthorization];
        }
        
        // 按照距离进行定位(1次/111km/100 次)
        //        _locationM.distanceFilter = 100;
        
        //kCLLocationAccuracyBestForNavigation  最适合导航
        //kCLLocationAccuracyBest; 最好的
        //kCLLocationAccuracyNearestTenMeters; 10米
        //kCLLocationAccuracyHundredMeters; 100米
        //kCLLocationAccuracyKilometer; 1000米
        //kCLLocationAccuracyThreeKilometers 3000米
        
        // 设置定位精确度
        _locationM.desiredAccuracy = kCLLocationAccuracyBest;
        
        // 允许后台定位(也有蓝条)
        // 注意:必须勾上后台模式
        //        _locationM.allowsBackgroundLocationUpdates = YES;
    }
    return _locationM;
}
#pragma mark - CLLocationManagerDelegate
/**
 *  当获取到用户信息时会调用该方法
 *
 *  @param manager   位置管理者
 *  @param locations 位置数组
 */
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    //    NSInteger i = [self.numLabel.text integerValue];
    //    ;
    //
    //    self.numLabel.text = [NSString stringWithFormat:@"%ld",(long)++i];
    //
    NSLog(@"定位到了");
    CLLocation *location = locations[0];
    NSLog(@"%f, %f",location.coordinate.latitude, location.coordinate.longitude);
    // 记录下定位到的经纬度
    [[NSUserDefaults standardUserDefaults]setObject:@[@(location.coordinate.latitude), @(location.coordinate.longitude)] forKey:@"coordinates"];
    self.location = location;
    // 针对只定位一次的请求,可以在获取到用户的位置之后,停止定位
    [manager stopUpdatingLocation];
    self.locationM = nil;
}
/**
 *  当授权状态改变时会调用该方法
 *
 *  @param manager 位置管理者
 *  @param status  授权状态
 */
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    
    //kCLAuthorizationStatusNotDetermined = 0, 用户未决定
    //kCLAuthorizationStatusRestricted, 受限制
    //kCLAuthorizationStatusDenied, 用户拒绝
    //kCLAuthorizationStatusAuthorizedAlways NS_ENUM_AVAILABLE(NA, 8_0), 前后台定位授权
    //kCLAuthorizationStatusAuthorizedWhenInUse NS_ENUM_AVAILABLE(NA, 8_0), 前台定位授权
    
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            NSLog(@"用户未决定");
            break;
            
        case kCLAuthorizationStatusRestricted:
            NSLog(@"受限制");
            break;
            
        case kCLAuthorizationStatusDenied:
            
            if ([CLLocationManager locationServicesEnabled]) { // 位置服务打开
                NSLog(@"用户拒绝");

            } else {
                NSLog(@"定位服务拒绝");
            }
            
            break;
            
        case kCLAuthorizationStatusAuthorizedAlways:
            NSLog(@"前后台定位授权");
            break;
            
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            NSLog(@"前台定位授权");
            break;
        default:
            break;
    }
    
}
/**
 *  当定位失败的时候会调用该方法
 *
 *  @param manager 位置管理者
 *  @param error   错误信息
 */
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"%@",error);
}

- (void)frogTwinkle {
    static NSInteger i = 0;
    i++;
    if (i % 2 == 0) {
        [self.frogBtn setBackgroundImage:[UIImage imageNamed:@"1"] forState:UIControlStateNormal];
    }
    else {
        [self.frogBtn setBackgroundImage:[UIImage imageNamed:@"2"] forState:UIControlStateNormal];
    }
}

- (void)createBigBubble {
    UIImageView *bigBubble = [[UIImageView alloc]init];
    bigBubble.image = [UIImage imageNamed:@"paopao"];
    bigBubble.size = CGSizeMake(150, 150);
    bigBubble.center = CGPointMake(screenW * 0.5, screenH * 0.4);
    bigBubble .alpha = 0;
    
    UILabel *bigBubbleLabel = [[UILabel alloc]init];
    bigBubbleLabel.frame = bigBubble.bounds;
    bigBubbleLabel.font = [UIFont systemFontOfSize:16.0];
    bigBubbleLabel.textColor = [UIColor whiteColor];
    bigBubbleLabel.textAlignment = NSTextAlignmentCenter;
    bigBubbleLabel.text = @"请输入";
    self.bigBubbleLabel = bigBubbleLabel;
    
    [bigBubble addSubview:bigBubbleLabel];
    
    self.bigBubble = bigBubble;
    [self.view addSubview:bigBubble];
    
}

// 退出键盘，气泡还原
- (void)resignKeyboard {
    if ([self.customTextField.text length] > 4) {
        [SVProgressHUD showInfoWithStatus:@"自定义活动最多4个字噢"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    }
    
    else{
        [self.customTextField resignFirstResponder];
        
        [self createBubbleTwinkleAnimation];
        //删除点击背景退出键盘的手势
        [self.view removeGestureRecognizer:self.tapOnBg];
        
        [UIView animateWithDuration:1.0 animations:^{
            for (WKBubble *bubble in _bubbles) {
                bubble.alpha = 1.0;
            }
            self.bigBubble.alpha = 0;
        }];
        if([self.customTextField.text isEqualToString:@""]) {
            self.customTextField.text = @"点此输入";;
        }
        // 记录下自定义的事件名称
        else {
            [[NSUserDefaults standardUserDefaults]setObject:self.customTextField.text forKey:@"customEvent"];
        }
    }
}
#pragma mark - text field delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [self clickBubble:self.customBubble];
    textField.text = @"";
    //添加点击背景退出键盘
    UITapGestureRecognizer *tapOnBg = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(resignKeyboard)];
    self.tapOnBg = tapOnBg;
    [self.view addGestureRecognizer:tapOnBg];
}

- (void)textFieldChange:(UITextField *)textField {
    self.bigBubbleLabel.text = textField.text;
}

- (void)frogBtnSingleClick {
    UIImageView *bubbleRec = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bubble_Rec"]];
    bubbleRec.bottom = self.frogBtn.top;
    bubbleRec.left = screenW * 0.5 - bubbleRec.width * 0.5;
    
    UILabel *bubbleRecLabel = [[UILabel alloc]init];
    bubbleRecLabel.text = @"要先选取一个活动噢～";
    bubbleRecLabel.font = [UIFont systemFontOfSize:11.0];
    bubbleRecLabel.textColor = [UIColor whiteColor];
    [bubbleRecLabel sizeToFit];
    bubbleRecLabel.center = CGPointMake(bubbleRec.width * 0.5, bubbleRec.height * 0.5 - 2);
    [bubbleRec addSubview:bubbleRecLabel];
    
    bubbleRec.alpha = 0;
    [self.view addSubview:bubbleRec];
    [UIView animateWithDuration:0.5 animations:^{
        bubbleRec.alpha = 1;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5 animations:^{
            bubbleRec.alpha = 0;
        } completion:^(BOOL finished) {
            [bubbleRec removeFromSuperview];
        }];
    }];

}


- (void)clickBubble:(WKBubble *)bubble {
    
    SystemSoundID soundID = 1;
    // 1.设置资源文件
    CFURLRef url = (__bridge CFURLRef)([[NSBundle mainBundle] URLForResource:@"bubble.mp3" withExtension:nil]);
    // 2.生成soundID
    AudioServicesCreateSystemSoundID(url, &soundID);
    // 3.播放音效
    AudioServicesPlaySystemSound(soundID);

    //如果用户不允许定位，弹窗提醒用户开启定位
    if (!([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"开启定位才发起活动哦" message:@"现在开启吧" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *goSetting = [UIAlertAction actionWithTitle:@"去开启" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"下次吧" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:goSetting];
        [alert addAction:cancel];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    
    if (self.location == nil) {
        [SVProgressHUD showInfoWithStatus:@"还在定位中..."];
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    NSArray *coordinates = [[NSUserDefaults standardUserDefaults]objectForKey:@"coordinates"];
    
    //如果点的不是自定义，则跳转至卡片页面
    if (![bubble isEqual:self.customBubble]) {
        
        
        for (WKBubble *bub in _bubbles) {
            bub.userInteractionEnabled = NO;
        }
        [UIView animateWithDuration:0.3 animations:^{
            bubble.transform = CGAffineTransformMakeScale(2, 2);
        }];

        [self boom:bubble];
        
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
        
        NSDictionary *dict = @{
                               @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                               @"lat" : [NSString stringWithFormat:@"%f", [[coordinates firstObject] floatValue]],
                               @"lng" : [NSString stringWithFormat:@"%f", [[coordinates lastObject] floatValue]],
                               @"eventTypeID" : bubble.info[@"id"]
                               };
        [mgr POST:[NSString stringWithFormat:@"%@Frog/creatEvent", URL] parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"创建事件 %@", responseObject);
            //记录当前事件的id
            NSString *fail = responseObject[@"state"];
            if ([fail isEqualToString:@"FAIL"]) {
                [SVProgressHUD showInfoWithStatus:responseObject[@"data"]];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                    return;
                });
            }
            //如果是新创建的活动，则记录下新的事件ID
            else {
//                if (![bubble.info[@"isGoing"] isEqual:@"1"]) {
                    [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"data"][@"myEventID"] forKey:@"eventID"];
//                }
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    WKCardViewController *cardVC = [[WKCardViewController alloc]init];
                    CATransition *anim = [CATransition animation];
                    anim.type = @"rippleEffect";
                    anim.duration = 1.0;
                    [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
                    [self.countDownTimer invalidate];
                    self.countDownTimer = nil;
                    [self presentViewController:cardVC animated:NO completion:nil];
                    [self.frogTwinkleTimer invalidate];
                    self.frogTwinkleTimer = nil;
                });
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@", error);
        }];
        
    }
    //点击的是自定义的气泡，则上方中央出现一个放大居中的气泡，所有气泡隐藏
    else {
        if ([self.customTextField.text isEqualToString:@""] || [self.customTextField.text isEqualToString:@"点此输入"]) {
            [self.customTextField becomeFirstResponder];
            [UIView animateWithDuration:1.0 animations:^{
                for (WKBubble *bubble in _bubbles) {
                    //所有气泡都隐藏
                    [bubble.layer removeAnimationForKey:@"animScale"];
                    [bubble.layer removeAnimationForKey:@"animOpacity"];
                    bubble.alpha = 0;
                    self.bigBubble.alpha = 1.0;
                }
            }];
        }
        
        else {
            for (WKBubble *bub in _bubbles) {
                bub.userInteractionEnabled = NO;
            }
            
            [UIView animateWithDuration:0.3 animations:^{
                bubble.transform = CGAffineTransformMakeScale(2, 2);
            }];
            

            [self boom:bubble];
            
            AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
            mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                             @"text/html",
                                                             @"image/jpeg",
                                                             @"image/png",
                                                             @"application/octet-stream",
                                                             @"text/json",
                                                             nil];
            
            NSDictionary *dict = @{
                                   @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                                   @"lat" : [NSString stringWithFormat:@"%f", [[coordinates firstObject] floatValue]],
                                   @"lng" : [NSString stringWithFormat:@"%f", [[coordinates lastObject] floatValue]],
                                   @"eventTypeID" : bubble.info[@"id"],
                                   @"custom_txt" : [[NSUserDefaults standardUserDefaults]objectForKey:@"customEvent"]
                                   };
            
            [mgr POST:[NSString stringWithFormat:@"%@Frog/creatEvent", URL] parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSLog(@"%@", responseObject);
                NSString *fail = responseObject[@"state"];
                if ([fail isEqualToString:@"FAIL"]) {
                    [SVProgressHUD showInfoWithStatus:responseObject[@"data"]];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [SVProgressHUD dismiss];
                        return;
                    });
                }
                //如果是新创建的活动，则记录下新的事件ID
                else {
                    if (![bubble.info[@"isGoing"] isEqual:@"1"]) {
                        [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"data"][@"myEventID"] forKey:@"eventID"];
                    }
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        WKCardViewController *cardVC = [[WKCardViewController alloc]init];
                        CATransition *anim = [CATransition animation];
                        anim.type = @"rippleEffect";
                        anim.duration = 1.0;
                        [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
                        [self.countDownTimer invalidate];
                        self.countDownTimer = nil;
                        [self presentViewController:cardVC animated:NO completion:nil];
                        [self.countDownTimer invalidate];
                        self.frogTwinkleTimer = nil;
                    });
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"%@", error);
            }];
            
        }
        
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationSlide;
}

- (void)createBubbleInitialAnimation {
    
    for (WKBubble *bubble in _bubbles) {
        bubble.transform = CGAffineTransformMakeScale(0, 0);
        bubble.transform = CGAffineTransformMakeTranslation(- bubble.position.x + screenW * 0.5, - bubble.position.y - 150);
    }
    
    [UIView animateWithDuration:1.5 animations:^{
        for (WKBubble *bubble in _bubbles) {
            bubble.transform = CGAffineTransformIdentity;
        }
    }];
}

- (void)createBubbleTwinkleAnimation{

    for (NSInteger i = 0; i < _bubbles.count; i++) {
        WKBubble *bubble = _bubbles[i];
        CAKeyframeAnimation *animScale = [CAKeyframeAnimation animation];
        
        animScale.keyPath = @"transform.scale";
        
        animScale.values = (i % 3 == 0) ? @[@1, @0.9] : (i % 3 == 1) ? @[@0.95, @1, @0.9] : @[@0.9, @1];
        animScale.duration = 2;
        animScale.repeatCount = MAXFLOAT;
        animScale.autoreverses = YES;
        
        CAKeyframeAnimation *animOpacity = [CAKeyframeAnimation animation];
        animOpacity.keyPath = @"opacity";
        animOpacity.values = (i % 3 == 1) ? @[@1, @0.7] : (i % 3 == 1) ? @[@0.85, @1, @0.7] : @[@0.7, @1];
        animOpacity.duration = 1;
        animOpacity.repeatCount = MAXFLOAT;
        animOpacity.autoreverses = YES;
        
        [bubble.layer addAnimation:animScale forKey:@"animScale"];
        [bubble.layer addAnimation:animOpacity forKey:@"animOpacity"];
        
    }
}


- (void)panGesture:(UIPanGestureRecognizer *)recoginizer {
    if (recoginizer.state == UIGestureRecognizerStateBegan){
        if (_pushBehavior) {
            [_animator removeBehavior:_pushBehavior];
        }
        _pushBehavior = [[UIPushBehavior alloc] initWithItems:@[recoginizer.view] mode:UIPushBehaviorModeContinuous];
        [_animator addBehavior:_pushBehavior];
    } else if (recoginizer.state == UIGestureRecognizerStateChanged) {
        CGPoint velocity = [recoginizer velocityInView:recoginizer.view];
        _pushBehavior.pushDirection = CGVectorMake(velocity.x / 10.0, velocity.y / 10.0);
    } else if (recoginizer.state == UIGestureRecognizerStateEnded||
               recoginizer.state == UIGestureRecognizerStateCancelled||
               recoginizer.state == UIGestureRecognizerStateFailed) {
        [_animator removeBehavior:_pushBehavior];
        _pushBehavior = nil;
    }
}

- (void)createDynamicBehaviors {
    UIDynamicBehavior *behavior = [[UIDynamicBehavior alloc] init];

    [behavior addChildBehavior:[self createCollisionBehaviorForObjects:_bubbles]];
    [behavior addChildBehavior:[self createItemBehavior]];

    _animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
    [_animator addBehavior:behavior];
}


- (UIDynamicBehavior *)createCollisionBehaviorForObjects:(NSArray *)objects {
    UICollisionBehavior *collisionBehavior = [[UICollisionBehavior alloc] initWithItems:objects];
    
    collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;
    
    collisionBehavior.collisionMode = UICollisionBehaviorModeEverything;
    
    [collisionBehavior addBoundaryWithIdentifier:@"boundry" fromPoint:CGPointMake(0, self.topLeftBtn.bottom) toPoint:CGPointMake(screenW, self.topLeftBtn.bottom)];
    return collisionBehavior;
}

- (UIDynamicItemBehavior *)createItemBehavior {
    
    UIDynamicItemBehavior *itemBehavior = [[UIDynamicItemBehavior alloc] initWithItems:_bubbles];
    
    itemBehavior.elasticity = 0.8;
    itemBehavior.allowsRotation = NO;
    itemBehavior.resistance = 0.3;
    itemBehavior.angularResistance = 1.0;
    return itemBehavior;
}

#pragma mark - 退出活动
- (void)resignActivity:(UIButton *)resignBtn {
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    
    NSDictionary *dict = @{
                           @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                           @"type" : @"3",
                           @"myEventID" : self.eventInfo[@"id"]
                           };
    
    [mgr POST:[NSString stringWithFormat:@"%@Frog/handleEvenet", URL] parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        //发出 关闭等待成功和同类匹配的链接 的通知
        [[NSNotificationCenter defaultCenter]postNotificationName:@"cancelRequests" object:nil userInfo:nil];
        
        WKBubbleViewController *bubbleVC = [[WKBubbleViewController alloc]init];
        CATransition *anim = [CATransition animation];
        anim.type = @"rippleEffect";
        anim.duration = 1.0;
        [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
        [UIApplication sharedApplication].keyWindow.rootViewController = bubbleVC;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

#pragma mark - 爆炸效果
- (void)boom:(UIControl *)btn{
    
    CAEmitterLayer *emitter = [CAEmitterLayer layer];
    
    [emitter setEmitterSize:CGSizeMake(CGRectGetWidth(btn.frame), CGRectGetHeight(btn.frame))];
    emitter.emitterPosition = CGPointMake(btn.frame.size.width /2.0, btn.frame.size.height / 2.0);
    emitter.emitterShape = kCAEmitterLayerCircle;
    emitter.emitterMode = kCAEmitterLayerOutline;
    [btn.layer addSublayer:emitter];
    
    CAEmitterCell *cell = [[CAEmitterCell alloc] init];
    [cell setName:@"zanShape"];
    
    cell.contents = (__bridge id _Nullable)([self createImageWithColor:[UIColor blackColor]].CGImage);
    cell.birthRate = 0;
    cell.lifetime = 0.6;
    cell.alphaSpeed = -2;
    
    cell.velocity = 20;
    cell.velocityRange = 20;
    emitter.emitterCells = @[cell];
    
    CABasicAnimation *effectLayerAnimation=[CABasicAnimation animationWithKeyPath:@"emitterCells.zanShape.birthRate"];
    [effectLayerAnimation setFromValue:[NSNumber numberWithFloat:1500]];
    [effectLayerAnimation setToValue:[NSNumber numberWithFloat:0]];
    [effectLayerAnimation setDuration:0.2f];
    [effectLayerAnimation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
    [emitter addAnimation:effectLayerAnimation forKey:@"ZanCount"];
}

-(UIImage*) createImageWithColor:(UIColor*) color
{
    CGRect rect = CGRectMake(5.0f, 5.0f, 5.0f, 5.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return [self circleImage:theImage];;
}

-(UIImage*) circleImage:(UIImage*) image{
    UIGraphicsBeginImageContext(image.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2);
    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
    CGRect rect = CGRectMake(0, 0, image.size.width , image.size.height );
    CGContextAddEllipseInRect(context, rect);
    CGContextClip(context);
    
    [image drawInRect:rect];
    CGContextAddEllipseInRect(context, rect);
    CGContextStrokePath(context);
    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newimg;
}

@end
